package com.huitone.smspfm.context.utils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;

import com.bin.common.utils.StringUtils;

public class ContextPropertiesUtils extends PropertyPlaceholderConfigurer {
	
	private static Logger logger = LogManager.getLogger(ContextPropertiesUtils.class);
	
	private static Map<String,String> propertyMap = new HashMap<String, String>();
	
	private static Resource[] locations = null;
	
	@Override
	public void setLocations(Resource... locations) {
		super.setLocations(locations);
		ContextPropertiesUtils.locations = locations;
	}
	
	@Override
	protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
			throws BeansException {
		super.processProperties(beanFactoryToProcess, props);
        for (Object key : props.keySet()) {
            String keyStr = StringUtils.objToString(key.toString()).trim();
            String value = StringUtils.objToString(props.getProperty(keyStr)).trim();
            propertyMap.put(keyStr, value);
        }
	}
	
	
	public synchronized static void reload() {
		
		if (locations != null) {
			
			for (Resource resource:locations) {
				
				Properties properties = new Properties();
				
				try {
					properties.load(resource.getInputStream());
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
				
				for (Object key : properties.keySet()) {
		            String keyStr = StringUtils.objToString(key.toString()).trim();
		            String value = StringUtils.objToString(properties.getProperty(keyStr)).trim();
		            propertyMap.put(keyStr, value);
		        }
			}
		}
	}
	
	public synchronized static String getProperty(String name) {
		
		if (propertyMap == null) return null;
		
        return StringUtils.toString(propertyMap.get(name));
    }
	
	public synchronized static List<String> getPropertys(String regex) {
		
		if (propertyMap == null) return null;
		
		List<String> resultList = new ArrayList<>();
		
		List<String> keyList = new ArrayList<>();
		
		Iterator<String> iterator = propertyMap.keySet().iterator();
		
		while(iterator.hasNext()) {
			String next = iterator.next();
			if (Pattern.compile(regex).matcher(next).matches()) {
				keyList.add(next);
			}
		}
		
		Collections.sort(keyList);
		
		for (String key:keyList) {
			resultList.add(propertyMap.get(key));
		}
		
		return resultList;
	}
}
